package com.wlyuan.open.scanner.repository.impl;

import com.wlyuan.open.scanner.assembler.ScannerContractAssembler;
import com.wlyuan.open.scanner.dao.entity.ContractIndexDO;
import com.wlyuan.open.scanner.dao.mapper.ContractIndexMapper;
import com.wlyuan.open.scanner.domain.contract.Contract;
import com.wlyuan.open.scanner.domain.contract.ContractConvert;
import com.wlyuan.open.scanner.repository.AttachRepository;
import com.wlyuan.open.scanner.repository.ContractRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.Optional;

/**
 * @author lijing
 * @description
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class ContractRepositoryImpl implements ContractRepository {
    private final ContractIndexMapper contractIndexMapper;
    private final AttachRepository attachRepository;
    private final BaseOrderRepository baseOrderRepository;

    @Override
    public List<Contract> list() {
        List<ContractIndexDO> list = contractIndexMapper.list();
        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyList();
        }
        logger.info("老数据数据量，size：{}", list.size());
        list.forEach(c -> process(c));
        return ContractConvert.convert(list);

    }

    @Override
    public Contract getById(Long contractId) {
        return Optional.ofNullable(contractId).map(id -> {
            var contract = contractIndexMapper.selectById(id);
            process(contract);
            return ContractConvert.convert(contract);
        }).orElse(null);
    }

    @Override
    public List<Long> getByTime(String startTime, String endTime) {
        return contractIndexMapper.getByTime(startTime, endTime);
    }

    @Override
    public List<Long> getByTenantIdTime(Long tenantId, String startTime, String endTime) {
        return contractIndexMapper.getByTenantIdTime(tenantId, startTime, endTime);
    }

    @Override
    public void getByTenantId(Long tenantId) {
        Optional.ofNullable(tenantId).ifPresent(tenant -> {
            var list = contractIndexMapper.getByTenantId(tenant);
            if (CollectionUtils.isEmpty(list)) {
                return;
            }
            list.forEach(contract -> {
                process(contract);
                var data = ContractConvert.convert(contract);
                baseOrderRepository.sync(ScannerContractAssembler.assemble(data));
            });
        });
    }

    private void process(ContractIndexDO data) {
        if (!Optional.ofNullable(data).isPresent()) {
            return;
        }
        //附件
        data.setAttachments(ContractConvert.convertAttach(attachRepository.getByContractId(data.getIndexId())));
    }
}
